<template>
  <div class="container">
    <!-- 顶部 -->
    <div class="title-wrap">
      <div class="title-text">
        <img src="../../assets/img/title_icon.png" alt="" />
        <span>手机传图</span>
      </div>
      <!-- 最小最大关闭 -->
      <div class="title-btns">
        <img src="../../assets/img/mini-w.png" @click="windowMin" alt="" />
        <img src="../../assets/img/close-w.png" @click="windowClose" alt="" />
      </div>
    </div>
    <!-- <div style="height: 64px"></div> -->
    <div class="content">
      <!-- 侧边栏 -->
      <div class="sidebar-wrap">
        <div class="qrcode-wrap" v-if="type != 2">
          <div class="qrcode-box">
            <img :src="qrImage" alt="" />
            <div class="invalid" v-if="invalid" @click="postUpPicQrUuid">
              <img src="../../assets/img/invalid_icon.png" alt="" />
              <span>已失效</span>
              <span>点击二维码刷新</span>
            </div>
          </div>
          <div class="qrcode-text">微信扫码开始传图</div>
        </div>
        <div class="btns-wrap" v-if="type != 2">
          <div class="sidebar-btn mb22" @click="getAllCurUserPhoto">
            <img src="../../assets/img/refresh_icon.png" alt="" />
            <span>立即刷新</span>
          </div>
          <div class="sidebar-btn mb22" @click="editList">
            <img src="../../assets/img/edit_list_icon.png" alt="" />
            <span>编辑列表</span>
          </div>
          <div class="sidebar-btn mb22" @click="selMultiple">
            <template v-if="type == 0">
              <img src="../../assets/img/more_image_icon.png" alt="" />
              <span>多图显示</span>
            </template>
            <template v-if="type == 1">
              <img src="../../assets/img/open_icon.png" alt="" />
              <span>打开{{ selIdx.length }}/4</span>
            </template>
          </div>
        </div>
        <div class="btns-wrap mt253" v-else>
          <div class="sidebar-btn mb22" @click="delImage">
            <img src="../../assets/img/delete_icon.png" alt="" />
            <span>删&nbsp;&nbsp;&nbsp;除</span>
          </div>
          <div class="sidebar-btn mb22" @click="clearImage">
            <img src="../../assets/img/clear_icon.png" alt="" />
            <span>清&nbsp;&nbsp;&nbsp;空</span>
          </div>
          <div class="sidebar-btn mb22" @click="exportImages">
            <img src="../../assets/img/export_icon.png" alt="" />
            <span>导&nbsp;&nbsp;&nbsp;出</span>
          </div>
          <div class="sidebar-btn mb22" @click="allExportImages">
            <img src="../../assets/img/all_export_icon.png" alt="" />
            <span>全部导出</span>
          </div>
          <div class="sidebar-btn mb22" @click="editList">
            <img src="../../assets/img/complete_icon.png" alt="" />
            <span>返&nbsp;&nbsp;&nbsp;回</span>
          </div>
        </div>
        <div class="sidebar-tips">
          <div class="tips-title">
            <i class="el-icon-warning"></i>
            <span>温馨提示</span>
          </div>
          <div class="tips-con">
            当前仅支持保存最新上传的30条记录，每条上传记录最多保存10天。
          </div>
        </div>
      </div>
      <div class="fun-wrap">
        <div class="not-data" v-if="list.length == 0 && notData">
          <img src="../../assets/img/not_data_icon.png" alt="" />
          <p>暂无图片上传记录</p>
        </div>
        <template v-else>
          <div class="fun-box" v-for="(item, index) in list" :key="index">
            <div class="fun-title">{{ item.title }}上传</div>
            <ul class="fun-list">
              <li
                class="fun-item"
                v-for="(vo, key) in item.urls"
                :key="'a' + key"
              >
                <el-image
                  :src="vo.downloadUrl"
                  @click="openWindow1(index + 'a' + key)"
                  fit="cover"
                  lazy
                >
                  <div slot="placeholder" class="image-slot">
                    加载中<span class="dot">...</span>
                  </div>
                </el-image>
                <div
                  class="multiple_choice"
                  @click="selImage(index, key)"
                  v-if="type != 0"
                >
                  <img
                    v-if="selIdx.indexOf(index + 'a' + key) >= 0"
                    src="../../assets/img/multiple_g_icon.png"
                    alt=""
                  />
                  <img
                    v-else
                    src="../../assets/img/multiple_k_icon.png"
                    alt=""
                  />
                </div>
              </li>
            </ul>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>
<script>
import mixin from "../../mixin/mixin";
const axios = require("axios");
import qrCode from "qrcode";
import request from "../../utils/request";
import { StringUtil } from "../../../../../static/utils/StringUtil";
import moment from "moment";
import JSZip from "jszip";
import FileSaver from "file-saver";
import {collectUserPoint} from '../../api/point'
export default {
  mixins: [mixin],
  name: "Picture",
  data() {
    return {
      qrImage: null,
      list: [],
      invalid: false,
      timer: null,
      type: 0, // 0.默认状态 1.多选状态 2.编辑状态
      selIdx: [],
      urls: [],
      notData: false,
    };
  },
  mounted() {
    console.log(this.$route);
    this.postUpPicQrUuid();
    this.getAllCurUserPhoto();
    collectUserPoint({ channel: 11 });
  },
  destroyed() {
    clearTimeout(this.timer);
  },
  methods: {
    /**
     * 获取二维码Uuid
     */
    postUpPicQrUuid() {
      let params = {};
      request({
        url: "/wechat/postUpPicQrUuid",
        method: "post",
        data: params,
      }).then((res) => {
        if (res.code == "0") {
          this.createQrcode(res.returnValue.qrUuid);
        }
      });
    },
    /**
     * 创建二维码
     */
    createQrcode(qrUuid) {
      let _this = this;
      let env = this.$readIniFile("data", "env");
      let envDomain =
        env === this.$CONST.global.developmentStr
          ? this.$CONST.global.developmentWxDomain
          : this.$CONST.global.productionWxDomain;
      let url = StringUtil.format(
        "https://{0}/h5-image-trans/index.html?qrCode={1}#/login",
        envDomain,
        qrUuid
      );
      qrCode.toDataURL(
        url,
        {
          errorCorrectionLevel: "L",
          type: "image/jpeg",
          margin: 0,
          scale: 10,
        },
        function (err, res) {
          if (err) {
            _this.qrImage = "";
          } else {
            _this.invalid = false;
            _this.qrImage = res;
            _this.timer = setTimeout(() => {
              _this.invalid = true;
            }, 180000);
          }
        }
      );
    },
    /**
     * 查询用户所有上传图片，默认10天
     */
    getAllCurUserPhoto() {
      this.type = 0;
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.9)",
        target: ".fun-wrap",
      });
      request({
        url: "/usermeta/getAllCurUserPhoto",
        method: "POST",
        data: {
          fileType: 1,
        },
      })
        .then((res) => {
          if (res.code == "0") {
            let list = res.returnValue;
            if (list.length == 0) {
              this.notData = true;
              this.list = [];
            } else {
              let arr = [];
              list.map((item) => {
                item.createTime = moment(
                  new Date(parseInt(item.gmtCreate))
                ).format("YYYY年MM月DD日");
                if (arr.length > 0) {
                  let bl = true;
                  for (let i = 0; i < arr.length; i++) {
                    if (arr[i].title == item.createTime) {
                      arr[i].urls.push(item);
                      bl = false;
                      break;
                    }
                  }
                  if (bl) {
                    arr.push({ title: item.createTime, urls: [item] });
                  }
                } else {
                  arr.push({ title: item.createTime, urls: [item] });
                }
              });
              this.list = arr;
            }
          }
          loading.close();
        })
        .catch((err) => {
          this.$message.error("网络异常！");
          loading.close();
        });
    },
    /**
     * 删除图片
     */
    delImage() {
      if (this.selIdx.length == 0) {
        this.$message.error("请先选择图片！");
        return;
      }
      this.$confirm("确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let ids = [];
          this.selIdx.map((item) => {
            let r = item.split("a");
            ids.push(this.list[r[0]].urls[r[1]].fileId);
          });
          this.deletePhotoByIds(ids);
        })
        .catch();
    },
    /**
     * 清空图片
     */
    clearImage() {
      if (this.list.length == 0) {
        this.$message.error("暂无记录");
        return;
      }
      this.$confirm("确定清空?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let ids = [];
          this.list.map((item) => {
            item.urls.map((vo) => {
              ids.push(vo.fileId);
            });
          });
          this.deletePhotoByIds(ids);
        })
        .catch();
    },
    /**
     * 调用删除或清空图片接口
     */
    deletePhotoByIds(ids) {
      request({
        url: "/usermeta/deletePhotoByIds",
        method: "POST",
        data: {
          ids: ids,
        },
      })
        .then((res) => {
          if (res.code == "0") {
            this.selIdx = [];
            this.$message.success("删除成功");
            this.getAllCurUserPhoto();
          }
        })
        .catch((err) => {
          this.$message.error("网络异常！");
        });
    },
    /**
     * 导出记录
     */
    exportImages() {
      if (this.selIdx.length == 0) {
        this.$message.error("请先选择图片！");
        return;
      }
      let urls = [];
      this.selIdx.map((item) => {
        let r = item.split("a");
        urls.push({
          filename: this.list[r[0]].urls[r[1]].displayName,
          url: this.list[r[0]].urls[r[1]].downloadUrl,
        });
      });
      this.zipDownload(urls);
    },
    /**
     * 全部导出
     */
    allExportImages() {
      if (this.list.length == 0) {
        this.$message.error("暂无导出记录");
        return;
      }
      let urls = [];
      this.list.map((item) => {
        item.urls.map((vo) => {
          urls.push({ filename: vo.displayName, url: vo.downloadUrl });
        });
      });
      this.zipDownload(urls);
    },
    /**
     * 压缩文件
     */
    zipDownload(urls) {
      let zip = new JSZip();
      let pall = [];
      urls.map((item) => {
        let p = this.getFile(item.url).then((res) => {
          zip.file(item.filename, res, { binary: true });
        });
        pall.push(p);
      });
      Promise.all(pall).then((res) => {
        zip.generateAsync({ type: "blob" }).then((content) => {
          // 生成二进制流
          let time = moment().format("YYYYMMDD");
          FileSaver.saveAs(content, "美丽科学手机传图" + time);
        });
      });
    },
    /**
     * 图片链接转base64
     * @param url
     * @returns {Promise<any>}
     */
    getFile(url) {
      return new Promise((resolve, reject) => {
        axios({
          method: "get",
          url: url,
          responseType: "blob",
        })
          .then((data) => {
            resolve(data.data);
          })
          .catch((error) => {
            reject(error.toString());
          });
      });
    },
    /**
     * 编辑列表
     */
    editList() {
      if (this.type == 2) {
        this.type = 0;
      } else {
        this.type = 2;
        this.selIdx = [];
      }
    },
    /**
     * 选择图片
     */
    selImage(index, key) {
      if (this.type != 0) {
        let val = this.selIdx.indexOf(index + "a" + key);
        if (val >= 0) {
          this.selIdx.splice(val, 1);
        } else {
          if (this.type == 1) {
            if (this.selIdx.length < 4) {
              this.selIdx.push(index + "a" + key);
            } else {
              this.$message.error("最多只能选择4张图片！");
            }
          } else {
            this.selIdx.push(index + "a" + key);
          }
        }
      }
    },
    /**
     * 选择多图显示
     */
    selMultiple() {
      if (this.type == 0) {
        this.type = 1;
        this.selIdx = [];
      } else if (this.type == 1) {
        this.openWindow();
      }
    },
    /**
     * 打开图片
     */
    openWindow1(selIdx) {
      if (this.type == 0) {
        this.$electron.ipcRenderer.send("close-resource-window", {
          metaId: "Preview",
        });
        let type = 0;
        let urls = [];
        let index = 0;
        this.list.map((item, i) => {
          item.urls.map((vo, key) => {
            urls.push({
              filename: vo.displayName,
              url: vo.downloadUrl,
            });
            if (i + "a" + key == selIdx) {
              index = urls.length - 1;
            }
          });
        });
        let data = { type, list: urls, index };
        localStorage.preview_params = JSON.stringify(data);
        this.$electron.ipcRenderer.send("showResourceHideWindow", {
          metaId: "Preview",
          userId: "",
        });
      }
    },
    /**
     * 打开图片
     */
    openWindow() {
      if (this.selIdx.length == 0) {
        this.$message.error("请先选择图片！");
        return;
      }
      this.$electron.ipcRenderer.send("close-resource-window", {
        metaId: "Preview",
      });
      //type 0.单图 1.2张图 2.3-4张图片
      let type = 0;
      if (this.selIdx.length == 2) {
        type = 1;
      } else if (this.selIdx.length > 2) {
        type = 2;
      }
      let urls = [],
        index = 0;
      if (this.selIdx.length == 1) {
        this.list.map((item, i) => {
          item.urls.map((vo, key) => {
            urls.push({
              filename: vo.displayName,
              url: vo.downloadUrl,
            });
            if (i + "a" + key == this.selIdx[0]) {
              index = urls.length - 1;
            }
          });
        });
      } else {
        this.selIdx.map((item) => {
          let r = item.split("a");
          urls.push({
            filename: this.list[r[0]].urls[r[1]].displayName,
            url: this.list[r[0]].urls[r[1]].downloadUrl,
          });
        });
      }
      let data = { type, list: urls, index };
      localStorage.preview_params = JSON.stringify(data);
      this.$electron.ipcRenderer.send("showResourceHideWindow", {
        metaId: "Preview",
        userId: "",
      });
      this.type = 0;
    },
    /**
     * 最小化
     */
    windowMin() {
      this.$electron.ipcRenderer.send("resource-window-minimize", {
        metaId: "Picture",
      });
    },
    /**
     * 关闭
     */
    windowClose() {
      this.$electron.ipcRenderer.send("close-resource-window", {
        metaId: "Picture",
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  min-height: 100vh;
  background: none;
  background-color: #fff;
  .title-wrap {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 64px;
    background-image: url("../../assets/img/title_bg.png");
    background-size: cover;
    -webkit-app-region: drag;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30px;
    box-sizing: border-box;
    z-index: 98;

    .title-text {
      display: flex;
      align-items: center;
      img {
        margin-right: 8px;
        width: 20px;
        height: 20px;
      }
      span {
        font-size: 18px;
        color: #fff;
      }
    }

    .title-btns {
      -webkit-app-region: no-drag;
      img {
        width: 14px;
        height: 14px;
        margin-left: 18px;
        cursor: pointer;
      }
    }
  }
  .content {
    display: flex;
    height: calc(100vh - 64px);
    .sidebar-wrap {
      position: relative;
      height: 100%;
      width: 280px;
      background: linear-gradient(136deg, #ffffff 0%, #f1f8ff 100%);
      background-image: url("../../assets/img/sidebar_bg.png");
      background-repeat: no-repeat;
      background-size: cover;

      .qrcode-wrap {
        margin: 67px 0 57px;
        text-align: center;
        .qrcode-box {
          position: relative;
          width: 178px;
          height: 178px;
          margin: 0 auto;
          border: 8px solid rgba(0, 133, 255, 0.14);
          .invalid {
            position: absolute;
            top: -8px;
            left: -8px;
            width: calc(100% + 16px);
            height: calc(100% + 16px);
            background-color: rgba(0, 0, 0, 0.7);
            display: flex;
            flex-direction: column;
            justify-content: center;
            z-index: 1;
            cursor: pointer;
            img {
              width: 48px;
              height: 40px;
              margin: 46px auto 8px;
            }
            span {
              margin-top: 5px;
              font-size: 16px;
              color: #fff;
            }
          }
        }
        img {
          width: 162px;
          height: 162px;
        }
        .qrcode-text {
          margin-top: 24px;
          font-size: 16px;
          color: #303133;
          text-align: center;
        }
      }
      .btns-wrap {
        &.mt253 {
          margin-top: 253px;
        }
        .sidebar-btn {
          width: 135px;
          height: 40px;
          margin: 0 auto;
          background-color: #0085ff;
          border-radius: 20px;
          display: flex;
          align-items: center;
          cursor: pointer;
          padding: 0 20px;
          box-sizing: border-box;
          &.mb22 {
            margin-bottom: 22px;
          }
          img {
            width: 20px;
            height: 20px;
            margin-right: 9px;
          }
          span {
            flex: 1;
            text-align: center;
            font-size: 16px;
            color: #fff;
            margin-top: -2px;
          }
        }
      }

      .sidebar-tips {
        position: absolute;
        bottom: 50px;
        left: 0;
        width: 100%;
        padding: 0 30px;
        box-sizing: border-box;
        .tips-title {
          display: flex;
          align-items: center;
          .el-icon-warning {
            font-size: 22px;
            margin-right: 8px;
            color: #f7b500;
          }
          span {
            font-size: 16px;
            color: #303133;
            margin-top: -2px;
          }
        }
        .tips-con {
          margin-top: 14px;
          font-size: 14px;
          color: #606266;
        }
      }
    }
    .fun-wrap {
      flex: 1;
      overflow-y: auto;
      height: calc(100vh - 64px);
      .not-data {
        margin-top: 200px;
        text-align: center;
        font-size: 16px;
        img {
          width: 360px;
          height: 360px;
          object-fit: cover;
        }
        p {
          margin-top: 15px;
          color: #303133;
          font-size: 16px;
        }
      }
      .fun-box {
        margin-top: 32px;
        .fun-title {
          padding: 0 32px;
          box-sizing: border-box;
          font-size: 14px;
          color: #606266;
        }
        .fun-list {
          list-style-type: none;
          display: flex;
          flex-wrap: wrap;
          padding-left: 20px;
          .fun-item {
            position: relative;
            width: 200px;
            height: 200px;
            margin: 12px 12px 0;
            /deep/ .el-image {
              width: 100%;
              height: 100%;
              .image-slot {
                width: 100%;
                height: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
              }
            }
            .multiple_choice {
              position: absolute;
              bottom: 17px;
              right: 17px;
              width: 36px;
              height: 36px;
              z-index: 1;
              cursor: pointer;
              background-color: rgba(0, 0, 0, 0.3);
              border-radius: 100%;
              img {
                width: 100%;
                height: 100%;
              }
            }
          }
        }
      }
    }
  }
}
</style>
